//
//  PopupView.swift
//  QZWM_User_new
//
//  Created by youai on 2019/4/24.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import UIKit

//基础的弹出类
class PopupBaseView : UIView {
    
    static let backgroundColor = UIColor(white: 0, alpha: 0.4)
    
    let container = UIView()
    
    ///初始化，如果width==0则为置底，否则为居中
    init(width:CGFloat,height:CGFloat,cornerRadius:CGFloat,onTop:Bool = false){
        super.init(frame: CGRect.zero)
        self.backgroundColor = PopupBaseView.backgroundColor
        addSubview(container)
        container.snp.makeConstraints { (make) in
            if width>0 {
                make.width.equalTo(width)
                make.height.equalTo(height)
                make.centerX.equalToSuperview()
                if !onTop {
                    make.centerY.equalToSuperview()
                }else{
                    make.top.equalTo(container.snp.bottom).multipliedBy(0.3)
                }
            }else{
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(height)
            }
        }
        container.cornerRadius(cornerRadius).clipsToBounds = true
    }

    func show(vc:UIViewController){
        vc.view.endEditing(true)
        self.alpha = 0
        vc.view.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
        }
    }
    
    func hide(){
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    @discardableResult
    func touchHideImplement(_ touches: Set<UITouch>, with event: UIEvent?)->Bool {
        if touches.count == 0 {
            return false
        }
        for touch in touches {
            let p = touch.location(in: container)
            if !container.point(inside: p, with: event){
                hide()
                return true
            }
        }
        return false
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//选择取消和确定的弹出类
class PopupConfirmBox : PopupBaseView {
    
    let noteLabel = UILabel()
    let okBtn = Button()
    
    init(info:String ,title:String){
//        assert(info.count > 0)
        let textWidth:CGFloat = 205
        noteLabel.frame = CGRect(origin: .zero, size: .init(width: textWidth, height: .greatestFiniteMagnitude))
        noteLabel.numberOfLines = 0
        noteLabel.font = UIFont.systemFont(ofSize: 14)
        noteLabel.textColor = .x333333
        noteLabel.text = info
        noteLabel.sizeToFit()
        let boxHeight = 200-42+noteLabel.frame.height
        super.init(width: 270, height: boxHeight, cornerRadius: 5)
        container.backgroundColor = .white
        container.drawLabel(text: title, fontSize: 13, textColor: .x666666) { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(container.snp.top).offset(18+25.0*0.5)
        }
        container.addSubview(noteLabel)
        noteLabel.textAlignment = .center
        noteLabel.snp.makeConstraints { (make) in
            make.width.equalTo(textWidth)
            make.height.equalTo(noteLabel.frame.height)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-20)
//            make.topEqSuperView(offset: 48)
//            make.top.equalToSuperview().offset(48)
        }
        
        container.drawView { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-48)
            make.height.equalTo(1)
        }.backgroundColor = .xF2F2F2
        
        container.drawView { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.equalTo(1)
            make.height.equalTo(48)
        }.backgroundColor = .xF2F2F2
        
        container.drawButton(title: "取消", titleColor: .x333333, fontSize: 15) { (make) in
            make.left.bottom.equalToSuperview()
            make.height.equalTo(48)
            make.width.equalToSuperview().multipliedBy(0.5)
        }.addTarget(self, action: #selector(_onCancelButtonClick), for: .touchUpInside) //.debugColor()
        
        container.drawButton(button: okBtn,title: "确定", titleColor: .white, fontSize: 15) { (make) in
            make.right.bottom.equalToSuperview()
            make.height.equalTo(48)
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        okBtn.addTarget(self, action: #selector(_onSureButtonClick), for: .touchUpInside)//.debugColor()
        okBtn.backgroundColor = .xFC4C02
    }
    
    var onCancelButtonClick : EMPTY_CLOSURE? = nil
    var onSureButtonClick : EMPTY_CLOSURE? = nil
//    var shouldHideOnCancel : Bool = true
    @objc func _onCancelButtonClick(){
//        if shouldHideOnCancel{
            hide()
//        }
        onCancelButtonClick?()
    }
    @objc func _onSureButtonClick(){
        hide()
        onSureButtonClick?()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.touchHideImplement(touches, with: event)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchHideImplement(_ touches: Set<UITouch>, with event: UIEvent?) -> Bool {
        return false
    }
}

//选择取消和确定的弹出类
class PopupConfirmImgBox : PopupBaseView {
    
    let noteLabel = UIImageView()
    
    init(imgname:String){
        assert(imgname.count > 0)
        let textWidth:CGFloat = 320
        if let image = UIImage.init(named: imgname) {
            let imgheight = image.size.height*textWidth/image.size.width
            noteLabel.frame = CGRect(origin: .zero, size: .init(width: textWidth, height: imgheight))
            noteLabel.image = image
//            noteLabel.sizeToFit()
            let boxHeight = noteLabel.frame.height + 50
            super.init(width: 340, height: boxHeight, cornerRadius: 5)
            container.backgroundColor = .white
            container.addSubview(noteLabel)
            noteLabel.contentMode = .scaleAspectFit
            noteLabel.snp.makeConstraints { (make) in
                make.width.equalTo(textWidth)
                make.height.equalTo(noteLabel.frame.height)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview().offset(-20)
            }
            let v = container.drawView({ (make) in
                make.left.equalToSuperview().offset(60)
                make.bottom.equalToSuperview().offset(-65)
                make.height.equalTo(25)
                make.width.equalTo(100)
            })
            v.backgroundColor = .clear
            v.isUserInteractionEnabled = true
            v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_onImgTapClick(tap:))))
        }
        else {
            super.init(width: 270, height: 48, cornerRadius: 5)
        }
        
        container.drawView { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-48)
            make.height.equalTo(1)
        }.backgroundColor = .xF2F2F2
        
        container.drawView { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.equalTo(1)
            make.height.equalTo(48)
        }.backgroundColor = .xF2F2F2
        
        container.drawButton(title: "不同意退出", titleColor: .x333333, fontSize: 15) { (make) in
            make.left.bottom.equalToSuperview()
            make.height.equalTo(48)
            make.width.equalToSuperview().multipliedBy(0.5)
        }.addTarget(self, action: #selector(_onCancelButtonClick), for: .touchUpInside) //.debugColor()
        
        let okBtn = container.drawButton(title: "同意使用", titleColor: .white, fontSize: 15) { (make) in
            make.right.bottom.equalToSuperview()
            make.height.equalTo(48)
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        okBtn.addTarget(self, action: #selector(_onSureButtonClick), for: .touchUpInside)//.debugColor()
        okBtn.backgroundColor = .xFC4C02
    }
    
    var onTapImgClick : ENTER_CLOSURE? = nil
    var onSureButtonClick : EMPTY_CLOSURE? = nil
    var onCancelButtonClick : EMPTY_CLOSURE? = nil
//    var shouldHideOnCancel : Bool = true
    
    @objc func _onImgTapClick(tap:UITapGestureRecognizer){
        onTapImgClick?()
    }
        
    @objc func _onCancelButtonClick(){
//        if shouldHideOnCancel{
            hide()
//        }
        
        onCancelButtonClick?()
    }
    @objc func _onSureButtonClick(){
        hide()
        onSureButtonClick?()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
//        self.touchHideImplement(touches, with: event)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//无按钮弹出类
class PopupBox : PopupBaseView {
    let infoLabel = UILabel()
    init(infoText:String? = "",onTop:Bool = false){
        let textWidth:CGFloat = 270-20-20
        infoLabel.frame = CGRect(origin: .zero, size: .init(width: textWidth, height: .greatestFiniteMagnitude))
        infoLabel.numberOfLines = 0
        infoLabel.font = UIFont.systemFont(ofSize: 12)
        infoLabel.textColor = .white
        infoLabel.text = infoText
        infoLabel.sizeToFit()
        let boxHeight = 136-21+infoLabel.frame.height
        super.init(width: 270, height: boxHeight, cornerRadius: 0,onTop:onTop)
        container.backgroundColor = .init(white: 0, alpha: 0.8)
        container.layer.cornerRadius = 15;
        
        container.addSubview(infoLabel)
        infoLabel.textAlignment = .center
        infoLabel.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        container.snp.remakeConstraints { (make) in
            make.centerX.equalToSuperview()
            if !onTop {
                make.centerY.equalToSuperview().offset(80)
            }else{
                make.top.equalTo(container.snp.bottom).multipliedBy(0.8)
            }
            make.width.height.equalTo(infoLabel.snp.size).offset(40)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var onSureButtonClick : EMPTY_CLOSURE? = nil
    var onHide : EMPTY_CLOSURE? = nil
    
    @objc func _onSureButtonClick(){
        hide()
        ( onSureButtonClick ?? onHide )?()
    }
    
    @objc func _onXButtonClick(){
        hide()
        onHide?()
    }
    
    override func show(vc: UIViewController) {
        super.show(vc: vc)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.hide()
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if self.touchHideImplement(touches, with: event) {
            onHide?()
        }
    }
}

//只有在一个关闭按钮的弹出类
class PopupSureBox : PopupBaseView {
    
    let infoLabel = UILabel()
    let titleLabel = UILabel()
    
    init(title:String,infoText:String? = "",sureText:String,hasXButton:Bool=false,onTop:Bool = false){
//        assert(infoText.count > 0)
        let textWidth:CGFloat = 270-20-20
        infoLabel.frame = CGRect(origin: .zero, size: .init(width: textWidth, height: .greatestFiniteMagnitude))
        infoLabel.numberOfLines = 0
        infoLabel.font = UIFont.systemFont(ofSize: 12)
        infoLabel.textColor = .x999999
        infoLabel.text = infoText
        infoLabel.sizeToFit()
        let boxHeight = 136-21+infoLabel.frame.height
        super.init(width: 270, height: boxHeight, cornerRadius: 5,onTop:onTop)
        container.backgroundColor = .white
        
        container.drawLabel(label:titleLabel, text: title, fontSize: 15, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-10)
        }
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
//        container.addSubview(infoLabel)
//        infoLabel.textAlignment = .center
//        infoLabel.snp.makeConstraints { (make) in
//            make.width.equalTo(textWidth)
//            make.height.equalTo(infoLabel.frame.height)
//            make.centerX.equalToSuperview()
//            make.top.equalToSuperview().offset(48)
//        }
        
        let button = container.drawButton(title: sureText, titleColor: .white, fontSize: 15) { (make) in
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(40)
        }
        button.drawGradientLayer(color1: .xFC4C02, color2: .xFC4C02, x1: -0.23, y1: 0.5, x2: 0.5, y2: 0.5)
//        button.cornerRadius(4).clipsToBounds = true 刻设置圆角
        button.addTarget(self, action: #selector(_onSureButtonClick), for: .touchUpInside)
        
        if hasXButton {
            container.drawButton(imageNamed: "") { (make) in
                make.right.equalToSuperview()
                make.top.equalToSuperview()
            }.addTarget(self, action: #selector(_onXButtonClick), for: .touchUpInside)
        }
        
        container.snp.remakeConstraints { (make) in
            make.width.equalTo(270)
            make.height.equalTo(titleLabel.snp.height).offset(70)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
    }
    
    var onSureButtonClick : EMPTY_CLOSURE? = nil
    var onHide : EMPTY_CLOSURE? = nil
    
    @objc func _onSureButtonClick(){
        hide()
        ( onSureButtonClick ?? onHide )?()
    }
    
    @objc func _onXButtonClick(){
        hide()
        onHide?()
    }
    
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if self.touchHideImplement(touches, with: event) {
            onHide?()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//从底层向上弹出的选择类
class PopupBottomView : PopupBaseView{
    init(title:String,items:[String],vc:BaseViewController){
        let height:CGFloat = CGFloat(43 + 50 + 5 + 50*items.count) + ((vc.tabBarItem.title == nil) ? vc.getSafeArea().bottom : 0 )
        super.init(width: 0, height: height , cornerRadius: 0)
        container.backgroundColor = .xF8F8F9
        
        for i in -1..<items.count+1 {
            let h : CGFloat = (i == -1) ? 42 : 49
            let textColor : UIColor = (i == -1) ? .x999999 : .x333333
            let top : CGFloat
            let text : String
            let fontSize : CGFloat
            if i == -1 {
                top = 0
                text = title
                fontSize = 15
            }else if i == items.count {
                top = CGFloat(50 * i) + 43 + 5
                text = "取消"
                fontSize = 16
            }else{
                top = CGFloat(50 * i) + 43
                text = items[i]
                fontSize = 16
            }
            let view = container.drawView { (make) in
                make.left.right.equalToSuperview()
                make.top.equalToSuperview().offset(top)
                make.height.equalTo(h)
            }
            if i == -1 {
                view.drawLabel(text: text, fontSize: fontSize, textColor: textColor) { (make) in
                    make.edges.equalToSuperview()
                }.textAlignment = .center
            }else{
                let button = view.drawButton(title: text, titleColor: textColor, fontSize: fontSize) { (make) in
                    make.edges.equalToSuperview()
                }
                button.tag = i
                if i<items.count {
                    button.addTarget(self, action: #selector(_onButtonClick(button:)), for: .touchUpInside)
                }else{
                    button.addTarget(self, action: #selector(onCancelClick(button:)), for: .touchUpInside)
                }
            }
            view.backgroundColor = .white
        }
    }
    
    var onSelectWithIdx : ((Int)->Void)? = nil
    
    @objc private func _onButtonClick(button:UIButton){
        onSelectWithIdx?(button.tag)
    }
    @objc private func onCancelClick(button:UIButton){
        hide()
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.touchHideImplement(touches, with: event) 
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class PopupBaseBottomView : UIView {
    
    static let backgroundColor = UIColor(white: 0, alpha: 0.4)
    let container = UIView()
    init(){
        super.init(frame: CGRect.zero)
        self.backgroundColor = PopupBaseView.backgroundColor
    }
    
    func show(vc:BaseViewController,heightMultiply:CGFloat=0.5){
        vc.view.endEditing(true)
        vc.view.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        addSubview(container)
        container.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(vc.safeView.snp.bottom)
            make.height.equalTo(vc.safeView.snp.height).multipliedBy(heightMultiply)
        }
        
        container.backgroundColor = .white        
        
        let iphoneX_EdgeInsetsPatch_ = BaseViewController.safeEdgeInsets!.top - 20
        if iphoneX_EdgeInsetsPatch_ > 0 {
            container.drawView { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(container.snp.bottom)
                make.height.equalTo(iphoneX_EdgeInsetsPatch_*2)
            }.backgroundColor = .white
        }
        
        self.alpha = 0

        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
        }
    }
    
    func hide(){
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { (_) in
            self.removeFromSuperview()
        }
    }

    var disableTouchHide : Bool = false

    @discardableResult
    func touchHideImplement(_ touches: Set<UITouch>, with event: UIEvent?)->Bool {
        if disableTouchHide {
            return false
        }
        if touches.count == 0 {
            return false
        }
        for touch in touches {
            let p = touch.location(in: container)
            if !container.point(inside: p, with: event){
                hide()
                return true
            }
        }
        return false
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
